package com.egg.basic.util;

import com.egg.basic.config.qiniu.QiniuConfig;
import com.egg.common.spring.util.SpringContextUtil;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 文件七牛云 工具类
 *
 * @author east
 */
@Slf4j
public class FileQiniuUtil {


    private static Auth auth;
    private static UploadManager uploadManager;

    public void setAuth(Auth initAuth) {
        auth = initAuth;
    }

    public void setUploadManager(UploadManager initUploadManager) {
        uploadManager = initUploadManager;
    }

    /**
     * 创建上传token
     *
     * @return
     */
    private static String createUpToken() {
        QiniuConfig bean = SpringContextUtil.getBean(QiniuConfig.class);
        String upToken = auth.uploadToken(bean.getBucket());
        return upToken;
    }

    /**
     * 文件后缀
     *
     * @param fileName
     * @return
     */
    private static String getSuffix(String fileName) {
        String suffix = fileName.substring(fileName.indexOf(".") + 1);
        return "." + suffix;
    }

    /**
     * 目录
     *
     * @param fileName
     * @return
     */
    private static String getDirectory(String fileName) {
        String directory;
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")) {
            directory = "/images";
        } else if (fileName.endsWith(".mp4")) {
            directory = "/videos";
        } else {
            directory = "/others";
        }
        return directory;
    }

    /**
     * 公有空间访问
     *
     * @param fileKey
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String publicUrl(String fileKey) {
        String domainOfBucket = getDomainOfBucket();
        String encodedFileName = null;
        try {
            encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            log.error("上传文件失败", e);
        }
        String finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        return finalUrl;
    }

    /**
     * 私有空间访问url
     *
     * @param fileKey
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String privateUrl(String fileKey) {
        String domainOfBucket = getDomainOfBucket();
        String encodedFileName = "";
        try {
            encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
        } catch (Exception e) {
            log.error("上传文件失败", e);
        }
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        //1小时，可以自定义链接过期时间
        long expireInSeconds = 3600;
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        return finalUrl;
    }

    /**
     * 获取外链域名
     *
     * @return
     */
    private static String getDomainOfBucket() {
        QiniuConfig bean = SpringContextUtil.getBean(QiniuConfig.class);
        return bean.getDomain();
    }

    private static DefaultPutRet getDefaultPutRet(MultipartFile file) {
        try {
            Response response = uploadManager.put(
                    file.getInputStream()
                    , null
                    , createUpToken()
                    , null
                    , null
            );
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet;
        } catch (Exception e) {
            log.error("上传文件失败", e);
        }
        return null;
    }

    /**
     * 上传公有访问
     *
     * @param file
     */
    public static String uploadPublic(MultipartFile file) {
        DefaultPutRet putRet = getDefaultPutRet(file);
        return publicUrl(putRet.key);
    }

    /**
     * 上传私有访问
     *
     * @param file
     */
    public static String uploadPrivate(MultipartFile file) {
        DefaultPutRet putRet = getDefaultPutRet(file);
        return privateUrl(putRet.key);
    }


}